package com.zq.learn.grpc;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * HelloController
 *
 * @author ZhangQi
 * @date 2020/6/1
 */
@RestController
public class HelloController {
  //服务端IP:Port
  private String target="localhost:8777";

  @Autowired
  private HelloClient helloClient;

  @GetMapping("/hello")
  public void hello(String name) throws InterruptedException {
    //创建通道
    ManagedChannel channel= ManagedChannelBuilder.forTarget(target).usePlaintext().build();
    try {
      //利用通道，创建客户端存根
      helloClient.setBlockingStub(channel);
      //调用服务端方法。
      helloClient.greet(name);
    }catch (Exception e){
      e.printStackTrace();
    }finally {
      //最终延时关闭通道
      channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }
  }
}
